package com.nhjf.admin.controller.teachers;

import com.alibaba.fastjson.JSONObject;
import com.nhjf.admin.common.util.MD5;
import com.nhjf.admin.common.util.SysProperties;
import com.nhjf.admin.controller.BaseController;
import com.nhjf.admin.util.Jurisdiction;
import com.nhjf.command.system.CreateRoleCommand;
import com.nhjf.command.system.CreateTeacherCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.model.student.Student;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.Courses;
import com.nhjf.model.teachers.OperationLog;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.qo.system.OrganizationQo;
import com.nhjf.pojo.qo.system.RoleQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.CoursesQo;
import com.nhjf.pojo.qo.teachers.OrganizationHasStudentQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.CoursesService;
import com.nhjf.service.teachers.OperationLogService;
import com.nhjf.service.teachers.TeachersService;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;


@Controller
@RequestMapping(value = "/teach")
public class TeachersController extends BaseController {

	@Autowired
	private TeachersService teachersService;
	@Autowired
	private OperationLogService  operationLogService;
	@Autowired
	private UserService userSerivce;
	/**
	 * 查询老师列表
	 * @param response
	 * @param request
	 * @param teachersQo
	 * @param stuQo
	 * @param model
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/teachlist")
	public String Coursescc(HttpServletResponse response,HttpServletRequest request, @ModelAttribute TeachersQo teachersQo,@ModelAttribute OrganizationHasStudentQo stuQo, Model model, @RequestParam(value="page", defaultValue="1")Integer page){

		try {
			if (teachersQo == null) {
				teachersQo = new TeachersQo();
			}
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role role=new Role();
			while(iter.hasNext()) {
				role=iter.next();
				break;
			}
			if("1".equals(role.getNumber())) {
				Pagination pagination = new Pagination();
				pagination.setPageSize(10);
				pagination.setCondition(teachersQo);
				pagination.setPageNo(page);
				model.addAttribute("teachersQo",teachersQo);
				pagination = teachersService.queryPagination(pagination);
				model.addAttribute("pagination", pagination);
				return "/teacher/teacher_list.html";
			}else if("2".equals(role.getNumber())) {
				TeachersQo tqo=new TeachersQo();
				tqo.setUserId(user.getId());
				tqo.setSeachOrganization(true);
				Teacher teacher=teachersService.queryUnique(tqo);
				if(teacher.getTraininginstitution()!=null && teacher.getTraininginstitution().getId()!=null) {
					teachersQo.setOrganizationId(teacher.getTraininginstitution().getId());
				}else {
					// 跳转到登录页面
					response.sendRedirect(request.getContextPath()+"/login");
				}
				//			stuQo.setOrganization();
				Pagination pagination = new Pagination();
				pagination.setPageSize(10);
				pagination.setCondition(teachersQo);
				pagination.setPageNo(page);
				model.addAttribute("teachersQo",teachersQo);
				pagination = teachersService.queryPagination(pagination);
				model.addAttribute("pagination", pagination);
				return "/teacher/teacher_list.html";
			}

		} catch (InvalidSessionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	@RequestMapping(value="/teacherView")
	public String Views(HttpServletResponse response,HttpServletRequest request,  TeachersQo teachersQo, Model model,String id) {
		try {
			SysProperties sysProperties=SysProperties.getInstance();
			//			 String filePath=sysProperties.get("imagePath")+"teacher/"+name+"."+extension;
			String filePahts=sysProperties.get("webPath")+"/img/";
			model.addAttribute("filePahts",filePahts);    
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Teacher teacher= teachersService.get(Long.parseLong(id));
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}else{
				if(teacher!=null) {
					model.addAttribute("teacher",teacher);
					return "/teacher/teacher_view.html";
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			return "500";
		}
		return "/error/error.html";
	}
	/**
	 * 根据id删除老师
	 * @param response
	 * @param request
	 * @param teachersQo
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/teacherDel")
	public String teacDel(HttpServletResponse response,HttpServletRequest request,  TeachersQo teachersQo, Model model,String id) {
		try {
			/*Teacher teacher=teachersService.get(Long.parseLong(id));  //找到id进行修改
			teacher.getUser().setItsusableornot(2);
			Teacher ts= teachersService.update(teacher);*/
			TeachersQo qo=new TeachersQo();
			qo.setSeachUser(true);
			qo.setTeacherId(Long.parseLong(id));
			Teacher teacher=teachersService.queryUnique(qo);  //找到id进行修改
			Long id1= teacher.getUser().getId();
			User user=new User();
			user=userSerivce.get(id1);
			user.setItsusableornot(2);
			User users= userSerivce.update(user);
			if(users!=null) {
				OperationLog operationLog=new OperationLog();
				operationLog.setOperationType(1);
				operationLog.setOperationDescription("删除老师!");
				operationLog.setUserId(user);
				operationLog.setOperationTime(new Date());
				operationLog.setOperationUserName(user.getUserName());
				operationLogService.save(operationLog);
				return "200";
			}

		} catch (Exception e) {
			// TODO: handle exception
			return "500";
		}
		return "500";
	}


	/**
	 * 重置密码
	 * @param response
	 * @param request
	 * @param teachersQo
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/teacherCzMima")
	public String teacCzMima(HttpServletResponse response,HttpServletRequest request, Model model,String id) {
		try {
			TeachersQo teachersQo=new TeachersQo();
			teachersQo.setSeachUser(true);
			teachersQo.setTeacherId(Long.parseLong(id));
			teachersQo.setSeachOrganization(true);
			Teacher tc=teachersService.queryUnique(teachersQo);
			model.addAttribute("names",tc.getName());
			UserQo qo=new UserQo();
			qo.setUserId(tc.getUser().getId());
			qo.setSeachRole(true);
			User user1=userSerivce.queryUnique(qo);
			user1.setUserPassword(MD5.MD5Encode("123456"));
			User user= userSerivce.update(user1);
			if(user!=null) {
				OperationLog operationLog=new OperationLog();
				operationLog.setOperationType(3);
				operationLog.setOperationDescription("重置老师密码!");
				operationLog.setUserId(user);
				operationLog.setOperationTime(new Date());
				operationLog.setOperationUserName(user.getUserName());
				operationLogService.save(operationLog);
				return "200";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
		return "500";
	}
	@RequestMapping("/teachertzadd")
	public String teachertzAdd() {

		return "/teacher/teacher_add.html";
	}
	@RequestMapping("/verifyAccount")
	@ResponseBody
	public String verifyAccount(CreateTeacherCommand command) {
		UserQo qo=new UserQo();
		if(StringUtils.isNotBlank(command.getAccountNumber())) {
			qo.setUserName(command.getAccountNumber());
			User user= userSerivce.queryUnique(qo);
			if(user!=null) {
				return "500";
			}else {
				return "200";
			}
		}else {
			return "200";
		}
		
		
		
	}
	/**
	 * 添加老师账号
	 * @param response
	 * @param request
	 * @param model
	 * @param teacher
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/teacherAdd",method=RequestMethod.POST)
	public String teacAdd(HttpServletResponse response,HttpServletRequest request,Model model,UserQo userQo,@ModelAttribute CreateTeacherCommand teacher,
			MultipartFile imgFile) {
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role role=new Role();
			while(iter.hasNext()) {
				role=iter.next();
				break;
			}
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}else{
				if("1".equals(role.getNumber())) {
					return "503";
				}
				//判断文件是否为空
				if (imgFile.isEmpty()) {
					return "404";
				}
				int returnTag = -1;
				// 获取图片原始文件名
				String originalFilename = imgFile.getOriginalFilename();
				System.out.println(originalFilename);

				//              文件名使用当前时间
				String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
				//              获取上传图片的扩展名(jpg/png/...)
				String extension = FilenameUtils.getExtension(originalFilename);
				String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
				boolean flag = false;
				// 判断文件格式是否合法
				for (String str : regular) {
					if (extension.equalsIgnoreCase(str)) {
						flag = true;
					}
				}
				if (!flag) {
					returnTag = 0;
					return "202";
				}
				// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
				String path = "/findimge/" + name + "." + extension;
				//图片上传的绝对路径
				SysProperties sysProperties=SysProperties.getInstance();
				String filePath=sysProperties.get("imagePath")+"teacher/"+name+"."+extension;
				//				 String filePahts=sysProperties.get("imagePath");
				//				 model.addAttribute("filePahts",filePahts);         获取路径
				String imgPath="teacher/"+name+"."+extension;
				File dir = new File(filePath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				// 上传图片
				imgFile.transferTo(new File(filePath));
				TeachersQo teachersQo=new TeachersQo();
				Teacher teacherss=new Teacher();
				User users=new User();
				userQo.setUserName(teacher.getPhoneNumber());
				users=userSerivce.queryUnique(userQo);
				if(users==null) {
					teachersQo.setPhoneNumber(teacher.getPhoneNumber()); 
					teacherss=teachersService.queryUnique(teachersQo);
					if(teacherss==null) {//判断此账号是否已存在
						TeachersQo teachersQo1=new TeachersQo();
						teachersQo1.setUserId(user.getId());
						teachersQo1.setSeachOrganization(true);
						Teacher teachers=teachersService.queryUnique(teachersQo1);
						Long id= teachers.getTraininginstitution().getId();
						teacher.setTraininginstitutionid(id);
						teacher.setAvatar(imgPath);
						teacher.setPassword(MD5.MD5Encode(teacher.getPassword()));
						teachersService.createTeacher(teacher);
						OperationLog operationLog=new OperationLog();
						operationLog.setOperationType(2);
						operationLog.setOperationDescription("新增老师!");
						operationLog.setUserId(user);
						operationLog.setOperationTime(new Date());
						operationLog.setOperationUserName(user.getUserName());
						operationLogService.save(operationLog);
						return "200";
					}else {
						return "201";
					}
				}else {
					return "201";
				}

			}
		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "500";
	}

}
